package com.authine.cloudpivot.ext.listener;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.Exceptions;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.applicationservice.authority.RoleApi;
import com.authine.cloudpivot.ext.utils.HttpClients;
import com.authine.common.util.ObjectMapperUtils;
import com.authine.hermes.app.launcher.service.AppService;
import com.authine.hermes.app.operation.admin.dto.clientobject.AppPublishDto;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.errorcode.ErrorCodeEnum;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * @ClassName MyDeliverCallback
 * @Description: TODO
 * @Author fj
 * @Date 2021/7/29
 * @Version V1.0
 **/
@Slf4j
public class MyDeliverCallback implements DeliverCallback {
    private static final AppService appService = ApplicationContextUtils.getBean(AppService.class);
    private static final RestTemplate restTemplate = ApplicationContextUtils.getBean(RestTemplate.class);
    private static final RoleApi roleApi = new RoleApi();

    @Override
    public void handle(String consumerTag, Delivery message) {
        // 获取消息内容
        log.info("==============consumerTag：{}, message：{}==============", consumerTag, JSONObject.toJSONString(message));
        String msg = new String(message.getBody(), StandardCharsets.UTF_8);

        // 获取应用部署信息
        AppPublishDto appPublishDto = ObjectMapperUtils.fromJSON(msg, AppPublishDto.class);
        log.info("appPublishDto：{}", JSONObject.toJSONString(appPublishDto));

//        // 获取所有应用列表
//        SingleResponse<List<AppPublishDto>> allApp = appService.getAllApp(RoleApi.PROJECT_CODE, "");
//        List<String> appCodeList = allApp.getData().stream().map(AppPublishDto::getAppCode).collect(Collectors.toList());
//        // fixme 只更新固买项目下的应用
//        if (!appCodeList.contains(appPublishDto.getAppCode())) {
//            return;
//        }
//
//        SingleResponse<?> response = getMenuTree(appPublishDto.getAppCode());
//
//        // 通过应用编码和类型查询资源表
//        String[] columns = new String[]{"appCode", "type"};
//        Operator[] operators = new Operator[]{Operator.EQ, Operator.EQ};
//        Object[] columnsVal = new Object[]{appPublishDto.getAppCode(), ResourceTypeEnum.APP.getCode()};
//        SingleResponse<BOList> appBOList = BoServiceUtils.findListByComplex(ModelConst.T_RESOURCE, columns, columnsVal, operators);
//        log.info("----------通过应用编码和类型获取资源数据：{}----------", JSONObject.toJSONString(appBOList));
//
//        // 资源表中不存在此应用，新增数据
//        if (appBOList.getData().getTotal() == 0) {
//            // 获取sort最大值
//            BigDecimal sort = Objects.requireNonNull(JdbcTemplateUtils.builder(ModelConst.T_RESOURCE)
//                    .selectField("MAX(sort)"))
//                    .queryForObject(BigDecimal.class);
//            roleApi.createResource(response.getData(), sort.intValue() + 1);
//        } else {
//            String appId = String.valueOf(appBOList.getData().getData().get(0).get("id"));
//            Integer appSort = ((BigDecimal) appBOList.getData().getData().get(0).get("sort")).intValue();
//            List<Map<String, Object>> resourceDataList = Lists.newArrayList();
//            SingleResponse<BOList> menuResourceBOList;
//            SingleResponse<BOList> tabsResourceBOList;
//            SingleResponse<BOList> buttonsResourceBOList;
//
//            // 获取资源数据
//            List<Map<String, Object>> appDataList = TypeReferenceUtils.readValueToList(JSONObject.toJSONString(response.getData()));
//            log.info("----------appDataList：{}----------", JSONObject.toJSONString(appDataList));
//            Map<String, Object> appDataMap = appDataList.get(0);
//            // 获取菜单项
//            if (appDataMap.get("appMenuItems") == null) {
//                return;
//            }
//            List<Map<String, Object>> appMenuItemList = TypeReferenceUtils.readValueToList(JSONObject.toJSONString(appDataMap.get("appMenuItems")));
//            appMenuItemList = appMenuItemList.stream()
//                    // 获取的资源树包含FOLDER和PAGE，只取类型为PAGE的数据
//                    .filter(appMenuItemMap -> "PAGE".equals(appMenuItemMap.get("menuItemType")))
//                    .collect(Collectors.toList());
//            log.info("----------appMenuItemList：{}----------", JSONObject.toJSONString(appMenuItemList));
//            for (Map<String, Object> appMenuDataMap : appMenuItemList) {
//                // 通过菜单项编码查询资源表，如果不存在，新增数据
//                menuResourceBOList = BoServiceUtils.findListBySimple(ModelConst.T_RESOURCE, "menuItemCode", appMenuDataMap.get("menuItemCode"));
//                if (menuResourceBOList.getData().getTotal() == 0) {
//                    Map<String, Object> appMenuMap = Maps.newHashMap();
//                    String appMenuId = SchemaHelper.getId();
//                    appMenuMap.put("id", appMenuId);
//                    appMenuMap.put("parent_id", appId);
//                    appMenuMap.put("type", ResourceTypeEnum.MENU.getCode());
//                    appMenuMap.put("name", appMenuDataMap.get("menuItemName"));
//                    appMenuMap.put("level", ResourceTypeEnum.MENU.ordinal());
//                    appMenuMap.put("sort", appSort);
//                    appMenuMap.put("appCode", appDataMap.get("appCode"));
//                    appMenuMap.put("menuCode", appMenuDataMap.get("menuCode"));
//                    appMenuMap.put("menuItemCode", appMenuDataMap.get("menuItemCode"));
//                    appMenuMap.put("leaf", false);
//                    resourceDataList.add(appMenuMap);
//                }
//                // 获取标签页
//                if (appMenuDataMap.get("TabsPanelContainers") == null) {
//                    continue;
//                }
//                List<Map<String, Object>> appTabsPanelList = TypeReferenceUtils.readValueToList(JSONObject.toJSONString(appMenuDataMap.get("TabsPanelContainers")));
//                String appMenuId = String.valueOf(menuResourceBOList.getData().getData().get(0).get("id"));
//                log.info("----------appTabsPanelList：{}----------", JSONObject.toJSONString(appTabsPanelList));
//                for (Map<String, Object> appTabsPanelDataMap : appTabsPanelList) {
//                    // 通过标签页id查询资源表，如果不存在，新增数据
//                    columns = new String[]{"appCode", "componentCode", "pageCode"};
//                    operators = new Operator[]{Operator.EQ, Operator.EQ, Operator.EQ};
//                    columnsVal = new Object[]{appPublishDto.getAppCode(), appTabsPanelDataMap.get("id"), appMenuDataMap.get("pageCode")};
//                    tabsResourceBOList = BoServiceUtils.findListByComplex(ModelConst.T_RESOURCE, columns, columnsVal, operators);
//                    if (tabsResourceBOList.getData().getTotal() == 0) {
//                        Map<String, Object> appTabsPanelMap = Maps.newHashMap();
//                        String tabsPanelId = SchemaHelper.getId();
//                        appTabsPanelMap.put("id", tabsPanelId);
//                        appTabsPanelMap.put("parent_id", appMenuId);
//                        appTabsPanelMap.put("type", ResourceTypeEnum.TABS.getCode());
//                        // 获取标签页名称
//                        Map<String, Object> propsMap = JSONObject.parseObject(JSONObject.toJSONString(appTabsPanelDataMap.get("props")));
//                        appTabsPanelMap.put("name", propsMap.get("tab"));
//                        appTabsPanelMap.put("level", ResourceTypeEnum.TABS.ordinal());
//                        appTabsPanelMap.put("sort", appSort);
//                        appTabsPanelMap.put("appCode", appDataMap.get("appCode"));
//                        appTabsPanelMap.put("componentCode", appTabsPanelDataMap.get("id"));
//                        appTabsPanelMap.put("groupCode", appMenuDataMap.get("groupCode"));
//                        appTabsPanelMap.put("pageCode", appMenuDataMap.get("pageCode"));
//                        appTabsPanelMap.put("leaf", false);
//                        resourceDataList.add(appTabsPanelMap);
//                    }
//                    // 获取菜单项
//                    if (appTabsPanelDataMap.get("Buttons") == null) {
//                        continue;
//                    }
//                    List<Map<String, Object>> appButtonList = TypeReferenceUtils.readValueToList(JSONObject.toJSONString(appTabsPanelDataMap.get("Buttons")));
//                    String tabsPanelId = String.valueOf(tabsResourceBOList.getData().getData().get(0).get("id"));
//                    for (Map<String, Object> appButtonDataMap : appButtonList) {
//                        // 通过标签页id查询资源表，如果不存在，新增数据
//                        columns = new String[]{"appCode", "componentCode", "pageCode"};
//                        operators = new Operator[]{Operator.EQ, Operator.EQ, Operator.EQ};
//                        columnsVal = new Object[]{appPublishDto.getAppCode(), appButtonDataMap.get("id"), appMenuDataMap.get("pageCode")};
//                        buttonsResourceBOList = BoServiceUtils.findListByComplex(ModelConst.T_RESOURCE, columns, columnsVal, operators);
//                        if (buttonsResourceBOList.getData().getTotal() == 0) {
//                            Map<String, Object> appButtonMap = Maps.newHashMap();
//                            String buttonId = SchemaHelper.getId();
//                            appButtonMap.put("id", buttonId);
//                            appButtonMap.put("parent_id", tabsPanelId);
//                            appButtonMap.put("type", ResourceTypeEnum.BUTTON.getCode());
//                            appButtonMap.put("level", ResourceTypeEnum.BUTTON.ordinal());
//                            appButtonMap.put("name", appButtonDataMap.get("name"));
//                            appButtonMap.put("sort", appSort);
//                            appButtonMap.put("appCode", appDataMap.get("appCode"));
//                            appButtonMap.put("componentCode", appButtonDataMap.get("id"));
//                            appButtonMap.put("groupCode", appMenuDataMap.get("groupCode"));
//                            appButtonMap.put("pageCode", appMenuDataMap.get("pageCode"));
//                            appButtonMap.put("leaf", true);
//                            resourceDataList.add(appButtonMap);
//                        }
//                    }
//                }
//            }
//            if (!CollectionUtils.isEmpty(resourceDataList)) {
//                BoServiceUtils.createBo(ModelConst.T_RESOURCE, resourceDataList);
//            }
//        }
    }

    /**
     * 通过应用编码获取页面元数据信息
     * @param appCode   应用编码
     * @return  响应结果
     */
    private SingleResponse<?> getMenuTree(String appCode) {
        HttpHeaders headers = HttpClients.buildHttpHeaders(appCode);
        HttpEntity<String> request = new HttpEntity<>(null, headers);
        // 获取请求地址
        String requestUrl = HttpClients.getUrl(appCode, RoleApi.SUFFIX_URL);
        log.info("application service request = {},requestUrl = {}", request, requestUrl);
        SingleResponse<?> response = restTemplate.getForObject(requestUrl, SingleResponse.class);
        log.info("----------application service response：{}----------------", response);
        if (response == null || response.getData() == null) {
            Exceptions.throwBizException(ErrorCodeEnum.GET_PERMISSION_EXCEPTION);
        }
        return response;
    }
}
